package com.group.project.hrms.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.group.project.hrms.entity.AttendanceShiftInfo;
import com.group.project.hrms.entity.CheckPointInfo;
import com.group.project.hrms.entity.RestTimeSettings;
import com.group.project.hrms.entity.ResultEntity.ResultEntity;
import com.group.project.hrms.service.IAttendanceShiftInfoService;
import com.group.project.hrms.service.ICheckPointInfoService;
import com.group.project.hrms.service.IRestTimeSettingsService;
import com.group.project.hrms.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
public class AttendanceShiftInfoController {

    @Autowired
    private IAttendanceShiftInfoService iAttendanceShiftInfoService;

    @Autowired
    private ICheckPointInfoService iCheckPointInfoService;

    @Autowired
    private IRestTimeSettingsService iRestTimeSettingsService;

    @Autowired
    private DateUtil dateUtil;

    @Autowired
    private BasicInfoUtil basicInfoUtil;

    @Autowired
    private VerificationUtil verificationUtil;

    @Autowired
    private LogUtil logUtil;

    /**
     * 该方法将接收前端传来的创建班次信息数据，向数据库创建班次及休息时段
     * @param map 前端传来的参数
     * @param request http请求
     * @return 标准返回值对象
     */
    @RequestMapping("/basic/createAttendanceShiftInfo")
    @ResponseBody
    public ResultEntity createAttendanceShiftInfo(@RequestBody Map map, HttpServletRequest request){
        ResultEntity resultEntity = new ResultEntity();
        Object staffName = request.getAttribute("staffName");
        Date date = new Date();
        Object startDate = map.get("startDate");
        Object endDate = map.get("endDate");
        Object restList = map.get("restList");
        Object shiftName = map.get("shiftName");
        Object minLateHours = map.get("minLateHours");
        Object minLeaveEarlyHours = map.get("minLeaveEarlyHours");
        Object minNeglectWorkHours = map.get("minNeglectWorkHours");
        if(null != startDate && null != endDate && null != shiftName && null != minLateHours && null != minLeaveEarlyHours && null != minNeglectWorkHours){
            AttendanceShiftInfo attendanceShiftInfo = new AttendanceShiftInfo();
            attendanceShiftInfo.setcTime(date);
            attendanceShiftInfo.setShiftId(UUIDUtil.createUUID());
            attendanceShiftInfo.setShiftName(shiftName.toString());
            attendanceShiftInfo.setStartCheckPointId(startDate.toString());
            attendanceShiftInfo.setEndCheckPointId(endDate.toString());

            CheckPointInfo startCheckPointInfo = iCheckPointInfoService.selectOneCheckPointInfoByCheckPointID(startDate.toString());
            CheckPointInfo endCheckPointInfo = iCheckPointInfoService.selectOneCheckPointInfoByCheckPointID(endDate.toString());
            Date startTime = startCheckPointInfo.getStandardTime();
            Date endTime = endCheckPointInfo.getStandardTime();
            Date start = dateUtil.getDateByPointDate("2022-01-02", startTime);
            Date end = dateUtil.getDateByPointDate("2022-01-02", endTime);
            if(start.getTime() > end.getTime()){
                start = dateUtil.getDateByPointDate("2022-01-01", startTime);
            }
            long f = end.getTime() - start.getTime();

            //System.out.println(f);

            List<String> rids = new ArrayList<>(); //用于存储休息时间段的表单IDs
            if(null != restList){
                try{
                    JSONArray restListArray = JSON.parseArray(JSON.toJSONString(restList));
                    Map<String, List<String>> resultMap = basicInfoUtil.doInsertRestTimeSettings(restListArray, rids);
                    rids = resultMap.get("ids");
                    List<String> total = resultMap.get("total");
                    //System.out.println(total.get(0));
                    f = f - Long.valueOf(total.get(0));
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            //System.out.println(f);
            float totalSeconds= f/1000;
            //System.out.println(totalSeconds);
            float totalMinutes= totalSeconds/60;
            //System.out.println(totalMinutes);
            float autoDayWorkHours = totalMinutes/60;
            //System.out.println(autoDayWorkHours);
            attendanceShiftInfo.setRestTimeIds(JSON.toJSONString(rids));
            attendanceShiftInfo.setAutoDayworkHours(dateUtil.getFloatWithOneBit(autoDayWorkHours));
            attendanceShiftInfo.setMinLateHours(Integer.parseInt(minLateHours.toString()));
            attendanceShiftInfo.setMinLeaveEarlyHours(Integer.parseInt(minLeaveEarlyHours.toString()));
            attendanceShiftInfo.setMinNeglectWorkHours(Integer.parseInt(minNeglectWorkHours.toString()));
            int i = iAttendanceShiftInfoService.insertAttendanceShiftInfo(attendanceShiftInfo);
            logUtil.insertSystemEventLog(staffName.toString(), date, "创建了考勤班次:" + shiftName, "考勤");
            if(i != 0){
                resultEntity.setCode("S");
                resultEntity.setMsg("创建成功");
                return resultEntity;
            }
        }
        resultEntity.setCode("F");
        resultEntity.setMsg("创建失败");
        return resultEntity;
    }

    /**
     * 该方法接收前端传入的删除参数，向数据库删除一个指定的班次
     * @param map 前端传入的删除参数
     * @param request http请求
     * @return 标准返回值对象
     */
    @RequestMapping("/basic/deleteAttendanceShiftInfo")
    @ResponseBody
    public ResultEntity deleteAttendanceShiftInfo(@RequestBody Map map, HttpServletRequest request){
        ResultEntity resultEntity = new ResultEntity();
        Object staffName = request.getAttribute("staffName");
        Object sid = map.get("shiftId");
        if(null != sid){

            //删除前的校验
            if(!verificationUtil.confirmDeleteShiftInfo(sid.toString())){
                resultEntity.setCode("F");
                resultEntity.setMsg("删除失败，该班次正在使用中");
                return resultEntity;
            }

            AttendanceShiftInfo attendanceShiftInfo = iAttendanceShiftInfoService.selectOneAttendanceShiftInfoByShiftID(sid.toString());
            String restTimesIds = attendanceShiftInfo.getRestTimeIds();
            if(!restTimesIds.isEmpty()){
                JSONArray jsonArray = JSON.parseArray(restTimesIds);
                for (Object obj : jsonArray
                     ) {
                    RestTimeSettings restTimeSettings = iRestTimeSettingsService.selectOneRestTimeSettingsByRestTimeId(obj.toString());
                    iRestTimeSettingsService.deleteRestTimeSettings(restTimeSettings);
                }
            }
            int i = iAttendanceShiftInfoService.deleteAttendanceShiftInfo(attendanceShiftInfo);
            logUtil.insertSystemEventLog(staffName.toString(), new Date(), "删除了考勤班次:" + attendanceShiftInfo.getShiftName(), "考勤");
            if(i != 0){
                resultEntity.setCode("S");
                resultEntity.setMsg("删除成功");
                return resultEntity;
            }
        }
        resultEntity.setCode("F");
        resultEntity.setMsg("删除失败");
        return resultEntity;
    }

}
